﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Input;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework.Media;
using Omnia.DataModels;
using Omnia.Enums;
using Omnia.Library;
using Omnia.Library.Extensions;
using System.Windows;

namespace Omnia.ViewModels
{
    public class GalleriesViewModel : ViewModelBase
    {
        #region Constructors
        PhotoChooserTask photoChoose = new PhotoChooserTask();

        public GalleriesViewModel()
        {
            photoChoose.Completed -= new EventHandler<PhotoResult>(photoChoose_Completed);
            photoChoose.Completed += new EventHandler<PhotoResult>(photoChoose_Completed);
            photoChoose.ShowCamera = true;
        }
        #endregion

        #region Collections
        public ObservableCollection<PictureInfo> MediaLibraryPictures
        {
            get
            {
                return new ObservableCollection<PictureInfo>();
            }
        }

        public ObservableCollection<PictureInfo> IsoSlatedPictures
        {
            get { return new ObservableCollection<PictureInfo>(GetIsoSlatedPictures()); }
        } 
        #endregion

        #region Selections
        private PictureInfo selectedIsoSlatedPicture;
        public PictureInfo SelectedIsoSlatedPicture
        {
            get { return selectedIsoSlatedPicture; }
            set
            {
                selectedIsoSlatedPicture = value;
                RaisePropertyChanged(() => SelectedIsoSlatedPicture);
                RaisePropertyChanged(() => SetIsoSlatedCommand);
                RaisePropertyChanged(() => DeletePictureCommand);
            }
        }

        /*
        private PictureInfo selectedMediaLibraryPicture;
        public PictureInfo SelectedMediaLibraryPicture
        {
            get { return selectedMediaLibraryPicture; }
            set
            {
                selectedMediaLibraryPicture = value;
                RaisePropertyChanged(() => SelectedMediaLibraryPicture);
                RaisePropertyChanged(() => SetMediaLibraryCommand);
            }
        }
        //*/
        #endregion

        #region Methods
        private IEnumerable<PictureInfo> GetMediaLibraryPictures()
        {
            MediaLibrary library = new MediaLibrary();
            PictureCollection collection = library.Pictures;
            if (collection.Count > 0)
            {
                IEnumerator<Picture> pictures = collection.GetEnumerator();
                while (pictures.MoveNext())
                {
                    Picture picture = pictures.Current;
                    string na = picture.Name;
                    yield return new PictureInfo() { FileName = pictures.Current.Name, StreamInfo = pictures.Current.GetThumbnail() };
                }
                pictures.Reset();
            }
            yield return null;
        }

        private IEnumerable<PictureInfo> GetIsoSlatedPictures()
        {
            if (!IsDesignMode)
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    string[] files = store.GetFileNames(@"\Background\*.*");
                    foreach (string f in files)
                    {
                        string fname = @"\Background\" + f;
                        using (Stream stream = IsolatedStorageFile.GetUserStoreForApplication().OpenFile(fname, FileMode.Open, FileAccess.Read))
                        {
                            byte[] buffer = stream.GetBytes();
                            yield return new PictureInfo() { FileName = fname, StreamInfo = new MemoryStream(buffer) };
                        }
                    }
                }
            }
            yield return null;
        }

        private void SetBackground(PictureInfo picture, ImageLocationValue location)
        {
            GlobalSettings.BackgroundImage = picture.FileName;
            GlobalSettings.Location = location;

            RaisePropertyChanged(() => DeletePictureCommand);
        }

        private void photoChoose_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                using (BinaryReader reader = new BinaryReader(e.ChosenPhoto))
                {
                    using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        string fileName = System.IO.Path.GetFileName(e.OriginalFileName);

                        if (!store.DirectoryExists(@"\Background\"))
                        {
                            store.CreateDirectory(@"\Background");
                        }

                        if (store.FileExists(@"\Background\" + fileName))
                        {
                            store.DeleteFile(@"\Background\" + fileName);
                        }

                        using (IsolatedStorageFileStream fileStream = store.OpenFile(@"\Background\" + fileName, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            using (BinaryWriter writer = new BinaryWriter(fileStream))
                            {
                                writer.Write(reader.ReadBytes(Convert.ToInt32(e.ChosenPhoto.Length)));
                            }

                            fileStream.Close();
                            fileStream.Dispose();
                        }

                    }
                }

                RaisePropertyChanged(() => IsoSlatedPictures);
            }

        }

        private void DeletePictureFromIsoSlatedStorage(PictureInfo picture)
        {
            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                store.DeleteFile(picture.FileName);
            }
            RaisePropertyChanged(() => IsoSlatedPictures);
        }
        #endregion

        #region Commands
        public ICommand SetIsoSlatedCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return SelectedIsoSlatedPicture != null; },
                    ExecuteCallback = delegate
                    {
                        SetBackground(SelectedIsoSlatedPicture, ImageLocationValue.Isolated);
                    }
                };
            }
        }

        /*
        public ICommand SetMediaLibraryCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return SelectedMediaLibraryPicture != null; },
                    ExecuteCallback = delegate
                    {
                        SetBackground(SelectedMediaLibraryPicture, ImageLocationValue.MediaLibrary);
                    }
                };
            }
        }
        //*/

        public ICommand OpenMediaLibraryCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        photoChoose.Show();
                    }
                };
            }
        }

        public ICommand DeletePictureCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return SelectedIsoSlatedPicture != null && GlobalSettings.BackgroundImage != SelectedIsoSlatedPicture.FileName; },
                    ExecuteCallback = delegate
                    {
                        if (MessageBox.Show(Application.Current.FindResource<string>("IDS_NOTE_GALLERY_CONFIRM_MESSAGE"), Application.Current.FindResource<string>("IDS_NOTE_GALLERY_CONFIRM_TITLE"), MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                        {
                            DeletePictureFromIsoSlatedStorage(SelectedIsoSlatedPicture);
                        }
                    }
                };
            }
        }
        #endregion
    }
}
